const { request, PageContent } = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var wxcache = require('../../../utils/wxcache.js');
var pay = require('../../../services/pay.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 初始化当前订单详情
    cur_order_detail: {},
    type : 1,
    receiveName : "",
    receiveMobile: "",
    receiveAddress: "",
    provinceList:[],
    cityList:[],
    array_provice:['-省-'],
    array_city:['-市-'],
    array_ad:['-区/县-'],
    index_provice:0,
    index_city:0,
    index_ad:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
      // 获取order ID
    var order_id = JSON.parse(options.goods_id);
      var type =  options.type;
      that.setData({
        type: type
      })
      var _cur_order_detail = [];

      if (type == 1){
        var opp = JSON.parse(options.provinceList);
        var opc = JSON.parse(options.cityList);
        that.setData({
          provinceList: JSON.parse(options.provinceList),
          cityList: JSON.parse(options.cityList),
          array_provice: JSON.parse(options.provinceList),
          array_city: JSON.parse(options.provinceList),
          array_ad: JSON.parse(options.cityList)
        })
        //从后端取物品信息
        var url = api.findgoodlist;
        wx.request({
          url: url,
          method: "POST",
          data: {bizType:2},
          success: function (res) {
            console.log(res.data.responseBody.campaignList)
            var res_data = res.data.responseBody.campaignList
            for (var i = 0; i < res_data.length; i++) {
              for (var j = 0; j < order_id.length; j++) {
                if (res_data[i].id == order_id[j].id) {
                  _cur_order_detail.push(res_data[i]);
                }
              }
            }
            that.setData({
              cur_order_detail: _cur_order_detail
            })
          }
        });
        
      } else if (type == 2){
        var uid = wxcache.get("userInfo").id;
        var query_url = api.findCart;
        //从后台取数据
        wx.request({
          url: query_url,
          method: 'GET',
          data: { userId: uid, pageNo: 1, pageSize: 500 },    //参数为键值对字符串
          success: function (res) {
            console.log("向后端获取购物车数据：" + res.data.responseBody.goodsCartListRespList);
            var res_arr = res.data.responseBody.goodsCartListRespList;
            var img_url = [];
            for (var i = 0; i < res_arr.length; i++) {
              for (var j = 0; j < order_id.length; j++){
                if (res_arr[i].goodsCart.id == order_id[j].id) {
                  img_url.push(res_arr[i].campaignResp.primaryImageUrl[0]);
                  _cur_order_detail.push({
                    primaryImageUrl: img_url,
                    count: res_arr[i].goodsCart.num,
                    id: res_arr[i].goodsCart.campaignId,
                    customerPrice: res_arr[i].campaignResp.customerPrice,
                    name: res_arr[i].campaignResp.name,
                    count: order_id[j].count
                  }); 
                }
              }
            }
            that.setData({
              cur_order_detail: _cur_order_detail,
              total_price: options.total_price
            })
          }
        })
      }
  },
  inputnamevalue : function(e){
    this.setData({
      receiveName:e.detail.value
    })
  },
  inputphonevalue: function (e) {
    this.setData({
      receiveMobile: e.detail.value
    })
  },
  inputaddressvalue: function (e) {
    this.setData({
      receiveAddress: e.detail.value
    })
  },
  /**
   * 去支付
   */
  orderCreate :function(){
    let _this = this;
    //收货人姓名
    var receiveName = _this.data.receiveName;
    //var receiveName = "山水";
    //收货人电话
    var receiveMobile = _this.data.receiveMobile;
    //手机号验证
    if (!(/^1[345678]\d{9}$/.test(receiveMobile))) {
      wx.showToast({
        title: '手机号码有误',
        duration: 2000,
        icon: 'none'
      });
      return false;
    }
    //收货人地址
    var receiveAddress = _this.data.receiveAddress;
    //下单人id
    var applicantId = wxcache.get("userInfo").id;
    //商品id数组
    var campaignId = [];
    for (var i = 0; i < _this.data.cur_order_detail.length; i++){
      campaignId.push( _this.data.cur_order_detail[i].id)
    }
    //商品合计总价
    var principal = 0;
    if (_this.data.type == 1){
      
      principal = Math.round(_this.data.cur_order_detail[0].customerPrice * 100, 0);
    } else if (_this.data.type == 2){
      principal = Math.round(_this.data.total_price * 100,0);
    }
    principal = principal >= 0 ? principal : 0
    //调取下单接口
    var order_url = api.goodOrderCreate;
    var data = {
      applicantId: applicantId,
      campaignId: campaignId,
      principal: principal,
      receiveName: receiveName,
      receiveMobile: receiveMobile,
      receiveAddress: receiveAddress
    };
    wx.request({
      url: order_url,
      method: 'POST',
      data: data, //参数为键值对字符串
      success: function (res) {
        console.log("向后端下单：" , res);
        if(res.data.message == "ok"){
          _this.pay(res.data.responseBody.orderId, principal);
        }
      }
    })
  },

  // 支付
  pay: function (orderId,principal) {
    //支付
    var data = {};
    data.payMoney = principal;

    data.body = "支付给锦旗国旅商品费用！";
    data.detail = "";
    data.attach = "";
    data.orderNo = orderId;


    pay.payOrder(data).then(function (res) {
      console.log(res)
      if (res.errMsg == "requestPayment:ok") {
        wx.showModal({
          title: '温馨提示',
          content: '支付完成!',
          showCancel: false,
          success: function (re) {
            wx.redirectTo({
              url: '/pages/market/my_order/my_order?tab=2'
            })
          }
        })
      }
    }).catch(function (res) {
      console.log(res)
      if (res.errMsg == "requestPayment:fail cancel") {
        wx.showModal({
          title: '温馨提示',
          content: '请在5分钟内支付完成',
          showCancel: false,
          success: function (re) {
            wx.redirectTo({
              url: '/pages/market/my_order/my_order?tab=2'
            })
          }
        })

      } else if (res.errMsg.startsWith("requestPayment:fail")) {
        wx.showModal({
          title: '提示',
          content: '支付失败，请稍后重试',
          showCancel: false,
          success: function (e) {
            wx.navigateTo({
              url: '/pages/market/my_order/my_order?tab=2',
            })
          }
        })
      }
    })
  },
  /**
   * 支付
   */
  goodPrePay: function (orderId,principal){
    //下单人id
    var applicantId = wxcache.get("userInfo").id;
    var pay_url = api.goodPrePay + "?p_u=" + applicantId;
    //支付金额
    var payMoney = principal;
    //订单号
    var orderNo = orderId;
    var body = "支付给锦旗国旅商品费用！";
    var data = {
      payMoney: payMoney,
      orderNo: orderNo,
      body: body
    };
    wx.request({
      url: pay_url,
      method: 'POST',
      data: data, //参数为键值对字符串
      success: function (res) {
        console.log("向后端调取支付接口：" , res);
        if (res.data.message == "ok") {
          console.log("支付成功");
        }
      }
    })
  },
  /**
   * tap申请取消订单
   */
  cancelOrderDlg: function () {
    const that = this;
    // 获取data中的cur_order_detail
    const cur_order_detail = this.data.cur_order_detail;
    // 将order_status状态设为1，即订单取消的状态
    cur_order_detail.order_status = "1";
    wx.showModal({
      title: `是否申请取消订单？`,
      confirmText: "确定",
      confirmColor: "#E45050",
      success: function (res) {
        // 点确定将页面设为订单取消的状态
        if (res.confirm) {
          that.setData({
            cur_order_detail: cur_order_detail
          });
        }
      }
    });
  },

  /**
   * 点击某一商品链接到该商品的详情页
   */
  toGoodsDetail: (e) => {
    // 获取当前订单的ID作为值传入url中
    const goods_id = e.currentTarget.id;
    PageContent.loadNavigate(`../../cart/goods_detail/goods_detail?goods_id=${goods_id}`);
  },
  selectProvice:function(e){
    this.setData({
      index_provice: e.detail.value
    })
  },
  selectCity: function (e) {
      this.setData({
        index_city: e.detail.value
      })
  },
  selectAd: function (e) {
        this.setData({
          index_ad: e.detail.value
        })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});